package org.example.service;

import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 产品分布服务
 * 控制不同时间段的放款产品分布
 */
@Service
public class ProductDistributionService {
    
    // 产品分布配置
    private static final Map<String, Double> PRODUCT_DISTRIBUTION = Map.of(
        "盈峰小贷", 0.30,  // 30%
        "浩瀚小贷", 0.50,  // 50%
        "新网银行", 0.15,  // 15%
        "江山小贷", 0.05   // 5%
    );
    
    // 浩瀚小贷余额限制（6亿）
    private static final BigDecimal HAOHAN_BALANCE_LIMIT = new BigDecimal("600000000");
    
    // 当前浩瀚小贷余额（需要在实际使用中维护）
    private BigDecimal currentHaohanBalance = BigDecimal.ZERO;
    
    /**
     * 根据放款日期获取产品名称
     * @param loanDate 放款日期
     * @param totalLoanAmount 总放款金额
     * @return 产品名称
     */
    public String getProductName(LocalDate loanDate, BigDecimal totalLoanAmount) {
        // 2023年7月-12月：只有浩瀚小贷
        if (loanDate.isBefore(LocalDate.of(2024, 1, 1))) {
            return "浩瀚小贷";
        }
        
        // 2024年1月后：多产品分布
        return selectProductByDistribution(totalLoanAmount);
    }
    
    /**
     * 根据分布选择产品
     */
    private String selectProductByDistribution(BigDecimal loanAmount) {
        // 检查浩瀚小贷余额限制
        if (currentHaohanBalance.add(loanAmount).compareTo(HAOHAN_BALANCE_LIMIT) > 0) {
            // 如果超过限制，从其他产品中选择
            return selectAlternativeProduct();
        }
        
        // 按分布概率选择产品
        double random = ThreadLocalRandom.current().nextDouble();
        double cumulative = 0.0;
        
        for (Map.Entry<String, Double> entry : PRODUCT_DISTRIBUTION.entrySet()) {
            cumulative += entry.getValue();
            if (random <= cumulative) {
                String product = entry.getKey();
                
                // 更新浩瀚小贷余额
                if ("浩瀚小贷".equals(product)) {
                    currentHaohanBalance = currentHaohanBalance.add(loanAmount);
                }
                
                return product;
            }
        }
        
        // 默认返回新网银行
        return "新网银行";
    }
    
    /**
     * 选择替代产品（当浩瀚小贷达到限制时）
     */
    private String selectAlternativeProduct() {
        // 重新计算其他产品的分布
        Map<String, Double> alternativeDistribution = new HashMap<>();
        double totalAlternative = 0.0;
        
        for (Map.Entry<String, Double> entry : PRODUCT_DISTRIBUTION.entrySet()) {
            if (!"浩瀚小贷".equals(entry.getKey())) {
                alternativeDistribution.put(entry.getKey(), entry.getValue());
                totalAlternative += entry.getValue();
            }
        }
        
        // 归一化分布
        for (Map.Entry<String, Double> entry : alternativeDistribution.entrySet()) {
            entry.setValue(entry.getValue() / totalAlternative);
        }
        
        // 按新的分布选择
        double random = ThreadLocalRandom.current().nextDouble();
        double cumulative = 0.0;
        
        for (Map.Entry<String, Double> entry : alternativeDistribution.entrySet()) {
            cumulative += entry.getValue();
            if (random <= cumulative) {
                return entry.getKey();
            }
        }
        
        return "新网银行";
    }
    
    /**
     * 获取当前浩瀚小贷余额
     */
    public BigDecimal getCurrentHaohanBalance() {
        return currentHaohanBalance;
    }
    
    /**
     * 获取浩瀚小贷剩余额度
     */
    public BigDecimal getRemainingHaohanQuota() {
        return HAOHAN_BALANCE_LIMIT.subtract(currentHaohanBalance);
    }
    
    /**
     * 重置余额（用于测试或重新开始）
     */
    public void resetBalance() {
        currentHaohanBalance = BigDecimal.ZERO;
    }
    
    /**
     * 获取产品分布统计
     */
    public Map<String, Object> getProductDistributionStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("productDistribution", PRODUCT_DISTRIBUTION);
        stats.put("haohanBalanceLimit", HAOHAN_BALANCE_LIMIT);
        stats.put("currentHaohanBalance", currentHaohanBalance);
        stats.put("remainingHaohanQuota", getRemainingHaohanQuota());
        stats.put("haohanUtilizationRate", 
                HAOHAN_BALANCE_LIMIT.compareTo(BigDecimal.ZERO) > 0 ? 
                currentHaohanBalance.divide(HAOHAN_BALANCE_LIMIT, 4, java.math.RoundingMode.HALF_UP).multiply(new BigDecimal("100")) : 
                BigDecimal.ZERO);
        return stats;
    }
    
    /**
     * 验证产品分布是否合理
     */
    public boolean validateDistribution(List<String> productNames) {
        Map<String, Long> counts = productNames.stream()
                .collect(java.util.stream.Collectors.groupingBy(
                        name -> name, 
                        java.util.stream.Collectors.counting()));
        
        int total = productNames.size();
        if (total == 0) return true;
        
        // 检查2024年后的分布
        long haohanCount = counts.getOrDefault("浩瀚小贷", 0L);
        long yingfengCount = counts.getOrDefault("盈峰小贷", 0L);
        
        double haohanRate = (double) haohanCount / total;
        double yingfengRate = (double) yingfengCount / total;
        
        // 允许一定的误差范围（±5%）
        boolean haohanValid = haohanRate >= 0.45 && haohanRate <= 0.55;
        boolean yingfengValid = yingfengRate >= 0.25 && yingfengRate <= 0.35;
        
        return haohanValid && yingfengValid;
    }
}
